package com.company.ems.controller;

import com.company.ems.dao.EmployeeDAO;
import com.company.ems.dao.EmployeeDAOImpl;
import com.company.ems.model.Employee;
import com.company.ems.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;

@WebServlet("/employee")
public class EmployeeServlet extends HttpServlet {
    private EmployeeDAO employeeDAO;

    @Override
    public void init() throws ServletException {
        employeeDAO = new EmployeeDAOImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        if (action == null) {
            action = "list";
        }

        switch (action) {
            case "add":
                showAddForm(request, response);
                break;
            case "edit":
                showEditForm(request, response);
                break;
            case "view":
                showEmployee(request, response);
                break;
            case "delete":
                deleteEmployee(request, response);
                break;
            default:
                listEmployees(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        if ("add".equals(action)) {
            addEmployee(request, response);
        } else if ("edit".equals(action)) {
            updateEmployee(request, response);
        } else {
            listEmployees(request, response);
        }
    }

    private void listEmployees(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String name = request.getParameter("name");
        String department = request.getParameter("department");
        String pageParam = request.getParameter("page");

        int page = 1;
        int pageSize = 5;

        if (pageParam != null && !pageParam.isEmpty()) {
            page = Integer.parseInt(pageParam);
        }

        int start = (page - 1) * pageSize;

        List<Employee> employees;
        int totalCount;

        if ((name != null && !name.isEmpty()) || (department != null && !department.isEmpty())) {
            employees = employeeDAO.findByPage(start, pageSize, name, department);
            totalCount = employeeDAO.findByCondition(name, department).size();
        } else {
            employees = employeeDAO.findByPage(start, pageSize, null, null);
            totalCount = employeeDAO.getTotalCount();
        }

        int totalPages = (int) Math.ceil((double) totalCount / pageSize);

        request.setAttribute("employees", employees);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("name", name);
        request.setAttribute("department", department);

        request.getRequestDispatcher("/employee/list.jsp").forward(request, response);
    }

    private void showAddForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/employee/add.jsp").forward(request, response);
    }

    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Employee employee = employeeDAO.findById(id);

        if (employee != null) {
            request.setAttribute("employee", employee);
            request.getRequestDispatcher("/employee/edit.jsp").forward(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/employee?error=Employee not found");
        }
    }

    private void showEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Employee employee = employeeDAO.findById(id);

        if (employee != null) {
            request.setAttribute("employee", employee);
            request.getRequestDispatcher("/employee/view.jsp").forward(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/employee?error=Employee not found");
        }
    }

    private void addEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        Employee employee = new Employee();
        employee.setName(request.getParameter("name"));
        employee.setDepartment(request.getParameter("department"));
        employee.setPosition(request.getParameter("position"));
        employee.setSalary(new BigDecimal(request.getParameter("salary")));
        employee.setEmail(request.getParameter("email"));
        employee.setPhone(request.getParameter("phone"));
        employee.setHireDate(LocalDate.parse(request.getParameter("hireDate")));
        employee.setCreatedBy(user.getId());

        boolean success = employeeDAO.save(employee);

        if (success) {
            response.sendRedirect(request.getContextPath() + "/employee?success=Employee added successfully");
        } else {
            request.setAttribute("error", "Failed to add employee");
            request.getRequestDispatcher("/employee/add.jsp").forward(request, response);
        }
    }

    private void updateEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));

        Employee employee = employeeDAO.findById(id);
        if (employee == null) {
            response.sendRedirect(request.getContextPath() + "/employee?error=Employee not found");
            return;
        }

        employee.setName(request.getParameter("name"));
        employee.setDepartment(request.getParameter("department"));
        employee.setPosition(request.getParameter("position"));
        employee.setSalary(new BigDecimal(request.getParameter("salary")));
        employee.setEmail(request.getParameter("email"));
        employee.setPhone(request.getParameter("phone"));
        employee.setHireDate(LocalDate.parse(request.getParameter("hireDate")));

        boolean success = employeeDAO.update(employee);

        if (success) {
            response.sendRedirect(request.getContextPath() + "/employee?success=Employee updated successfully");
        } else {
            request.setAttribute("error", "Failed to update employee");
            request.setAttribute("employee", employee);
            request.getRequestDispatcher("/employee/edit.jsp").forward(request, response);
        }
    }

    private void deleteEmployee(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        int id = Integer.parseInt(request.getParameter("id"));

        boolean success = employeeDAO.delete(id);

        if (success) {
            response.sendRedirect(request.getContextPath() + "/employee?success=Employee deleted successfully");
        } else {
            response.sendRedirect(request.getContextPath() + "/employee?error=Failed to delete employee");
        }
    }
}